<?php
namespace App\Services\Tool;

use Illuminate\Support\Facades\Lang;
use Log;

class GeneralTool
{
    /**
     * 建立唯一号（可以用来生成订单号，产品号）
     * @return string
     */
    public static function only_no()
    {
        return date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    }

    /**
     * 保存图片
     * @param $file
     * @param $path 模块区分
     * @return string
     */
    public function saveImage($file, $path = 4, $type = 0)
    {
        //获得图片的名字
        if ($file != null) {
            $clientName = $file->getClientOriginalName() . rand(1, 1000);
            //获得格式rand(10,100)
            $extension = $file->getClientOriginalExtension();
            if ($extension != null && !empty($extension)) {
                $newName = md5(date('ymdhis') . $clientName) . "." . $extension;
            } else {
                if ($type == 0) {
                    //前后预览图
                    $newName = md5(date('ymdhis') . $clientName) . ".jpg";
                } else {
                    //前后打印图
                    $newName = md5(date('ymdhis') . $clientName) . ".png";
                }
            }
            $file->move(public_path() . "/images/" . $path, $newName);
            $src_img = public_path() . "/images/" . $path . '/' . $newName;
            $dst_img = public_path() . "/thumbnail/" . $path . '/' . $newName;
            $this->mkFolder(public_path() . "/thumbnail/" . $path . '/');
            $isThumbnail = $this->img2thumb($src_img, $dst_img, $width = 200, $height = 300, $cut = 0, $proportion = 0.3);
            return $path . '/' . $newName;
        } else {
            return "";
        }

    }

    public function saveImage1($file, $path = 1, $type = '.png')
    {
        //获得图片的名字
        if ($file != null) {
            $clientName = $file->getClientOriginalName();
            //获得格式rand(10,100)
            $extension = $file->getClientOriginalExtension();
            if ($extension != null && !empty($extension)) {
                $newName = md5(date('ymdhis') . $clientName) . "." . $extension;
            } else {
                if ($type == 'image/png; charset=binary') {
                    $newName = md5(date('ymdhis') . $clientName) . ".png";
                } else if ($type == 'image/gif; charset=binary') {
                    $newName = md5(date('ymdhis') . $clientName) . ".gif";
                } else if ($type == 'image/jpeg; charset=binary') {
                    $newName = md5(date('ymdhis') . $clientName) . ".jpg";
                } else {
                    $newName = md5(date('ymdhis') . $clientName) . ".png";
                }
            }
            $file->move(public_path() . "/images/" . $path, $newName);
            $src_img = public_path() . "/images/" . $path . '/' . $newName;
            $dst_img = public_path() . "/thumbnail/" . $path . '/' . $newName;
            $this->mkFolder(public_path() . "/thumbnail/" . $path . '/');
            $isThumbnail = $this->img2thumb($src_img, $dst_img, $width = 200, $height = 300, $cut = 0, $proportion = 0.5);
            return $path . '/' . $newName;
        } else {
            return "";
        }

    }

    //判断图片类型
    function emu_getallheaders()
    {
        foreach ($_SERVER as $name => $value) {
            if (substr($name, 0, 5) == 'HTTP_') {
                $name = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))));
                $headers[$name] = $value;
            } else if ($name == "CONTENT_TYPE") {
                $headers["Content-Type"] = $value;
            } else if ($name == "CONTENT_LENGTH") {
                $headers["Content-Length"] = $value;
            }
        }
        return $headers;
    }


    /**
     * 判断文件夹是否存在 不存在创建
     * @param $path
     */
    function mkFolder($path)
    {
        if (is_dir($path)) {//已经是目录了就不用创建
            return true;
        }
        if (is_dir(dirname($path))) {//父目录已经存在，直接创建
            return mkdir($path);
        }
        $this->mkFolder(dirname($path));//从子目录往上创建
        return mkdir($path);//因为有父目录，所以可以创建路径
    }

    //对象转化成数组
    function objectToArray($e)
    {
        $e = (array)$e;
        foreach ($e as $k => $v) {
            if (gettype($v) == 'resource') return;
            if (gettype($v) == 'object' || gettype($v) == 'array')
                $e[$k] = (array)$this->objectToArray($v);
        }
        return $e;
    }

    //数组转化成对象
    function arrayToObject($e)
    {
        if (gettype($e) != 'array') return;
        foreach ($e as $k => $v) {
            if (gettype($v) == 'array' || getType($v) == 'object')
                $e[$k] = (object)$this->arrayToObject($v);
        }
        return (object)$e;
    }

    //获取文件
    public function getFile()
    {
        $path = $this->getImageAbsolutePath('place.json');
        $handle = fopen($path, 'r');
        $content = '';
        while (!feof($handle)) {
            $content .= fread($handle, 8080);
        }
        fclose($handle);
        return $content;
    }

    /**
     * 16进制颜色转RGB
     * @param $hex
     * @return array
     */
    function hex2rgb($hex)
    {
        $hex = str_replace("#", "", $hex);

        if (strlen($hex) == 3) {
            $r = hexdec(substr($hex, 0, 1) . substr($hex, 0, 1));
            $g = hexdec(substr($hex, 1, 1) . substr($hex, 1, 1));
            $b = hexdec(substr($hex, 2, 1) . substr($hex, 2, 1));
        } else {
            $r = hexdec(substr($hex, 0, 2));
            $g = hexdec(substr($hex, 2, 2));
            $b = hexdec(substr($hex, 4, 2));
        }

        return array('r' => $r, 'g' => $g, 'b' => $b);
    }

    /**
     * 保存色块
     */
    public function saveColorBlock($color_code)
    {
        $color_code = str_replace("#", "", $color_code);
        $imageUrl = "c/" . $color_code . ".png";
        $img = imagecreate(128, 128);
        //给图片分配颜色
        $rgb = $this->hex2rgb($color_code);
        imagecolorallocate($img, $rgb['r'], $rgb['g'], $rgb['b']);
        imagepng($img, public_path() . "/images/" . $imageUrl);
        return $imageUrl;
    }

    /**
     * 获取图片绝对路径
     * @param $path
     * @return string
     */
    public function getImageAbsolutePath($path)
    {
        return asset('images/' . $path);
    }

    /**
     * 获取缩略图绝对路径
     * @param $path
     * @return string
     */
    public function getImageThumbnailAbsolutePath($path)
    {
        return asset('thumbnail/' . $path);
    }

    /**
     * 生成缩略图
     * @author chenxd
     * @param string     源图绝对完整地址{带文件名及后缀名}
     * @param string     目标图绝对完整地址{带文件名及后缀名}
     * @param int        缩略图宽{0:此时目标高度不能为0，目标宽度为源图宽*(目标高度/源图高)}
     * @param int        缩略图高{0:此时目标宽度不能为0，目标高度为源图高*(目标宽度/源图宽)}
     * @param int        是否裁切{宽,高必须非0}
     * @param int /float  缩放{0:不缩放, 0<this<1:缩放到相应比例(此时宽高限制和裁切均失效)}
     * @return boolean
     */
    function img2thumb($src_img, $dst_img, $width = 75, $height = 75, $cut = 0, $proportion = 0)
    {
        if (!is_file($src_img)) {
            return false;
        }
        $ot = $this->fileext($dst_img);
        $otfunc = 'image' . ($ot == 'jpg' ? 'jpeg' : $ot);
        $srcinfo = getimagesize($src_img);
        $src_w = $srcinfo[0];
        $src_h = $srcinfo[1];
        $type = strtolower(substr(image_type_to_extension($srcinfo[2]), 1));
        $createfun = 'imagecreatefrom' . ($type == 'jpg' ? 'jpeg' : $type);

        $dst_h = $height;
        $dst_w = $width;
        $x = $y = 0;

        /**
         * 缩略图不超过源图尺寸（前提是宽或高只有一个）
         */
        if (($width > $src_w && $height > $src_h) || ($height > $src_h && $width == 0) || ($width > $src_w && $height == 0)) {
            $proportion = 1;
        }
        if ($width > $src_w) {
            $dst_w = $width = $src_w;
        }
        if ($height > $src_h) {
            $dst_h = $height = $src_h;
        }

        if (!$width && !$height && !$proportion) {
            return false;
        }
        if (!$proportion) {
            if ($cut == 0) {
                if ($dst_w && $dst_h) {
                    if ($dst_w / $src_w > $dst_h / $src_h) {
                        $dst_w = $src_w * ($dst_h / $src_h);
                        $x = 0 - ($dst_w - $width) / 2;
                    } else {
                        $dst_h = $src_h * ($dst_w / $src_w);
                        $y = 0 - ($dst_h - $height) / 2;
                    }
                } else if ($dst_w xor $dst_h) {
                    if ($dst_w && !$dst_h)  //有宽无高
                    {
                        $propor = $dst_w / $src_w;
                        $height = $dst_h = $src_h * $propor;
                    } else if (!$dst_w && $dst_h)  //有高无宽
                    {
                        $propor = $dst_h / $src_h;
                        $width = $dst_w = $src_w * $propor;
                    }
                }
            } else {
                if (!$dst_h)  //裁剪时无高
                {
                    $height = $dst_h = $dst_w;
                }
                if (!$dst_w)  //裁剪时无宽
                {
                    $width = $dst_w = $dst_h;
                }
                $propor = min(max($dst_w / $src_w, $dst_h / $src_h), 1);
                $dst_w = (int)round($src_w * $propor);
                $dst_h = (int)round($src_h * $propor);
                $x = ($width - $dst_w) / 2;
                $y = ($height - $dst_h) / 2;
            }
        } else {
            $proportion = min($proportion, 1);
            $height = $dst_h = $src_h * $proportion;
            $width = $dst_w = $src_w * $proportion;
        }

        $src = $createfun($src_img);
        $dst = imagecreatetruecolor($width ? $width : $dst_w, $height ? $height : $dst_h);
        $white = imagecolorallocate($dst, 255, 255, 255);
        imagefill($dst, 0, 0, $white);

        if (function_exists('imagecopyresampled')) {
            imagecopyresampled($dst, $src, $x, $y, 0, 0, $dst_w, $dst_h, $src_w, $src_h);
        } else {
            imagecopyresized($dst, $src, $x, $y, 0, 0, $dst_w, $dst_h, $src_w, $src_h);
        }
        $otfunc($dst, $dst_img);
        imagedestroy($dst);
        imagedestroy($src);
        return true;
    }

    /**
     * 文件提取
     * @param $file
     * @return mixed
     */
    function fileext($file)
    {
        return pathinfo($file, PATHINFO_EXTENSION);
    }

    /**
     * 返回格式
     */
    public static function createResult($result, $state)
    {
        return array('message' => Lang::get('globalcodes.' . $state), 'result' => ($result == "" ? (object)array() : $result), 'state' => $state);
    }

    /**
     * 判断图片格式
     */
    public static function switc($name, $type)
    {
        switch ($type) {
            case 'image/jpeg':
                $name .= '.jpg';
                return $name;
            case 'image/png':
                $name .= '.png';
                return $name;
            case 'image/gif ':
                $name .= '.gif';
                return $name;
            case 'image/bmp':
                $name .= '.bmp';
                return $name;
            default:
                return '格式不正确';
        }
    }


    /**
     * 计算页面执行时间
     *
     * @access public
     *
     * @return string
     **/
    function loadtime()
    {
        if (defined('LARAVEL_START') == true) {
            return number_format(microtime(true) - LARAVEL_START, 4);
        } else {
            return 0.0000;
        }
    }


    /**
     *    计算剩余时间
     *    参数：
     *        时间单位秒
     */
    public static function residualTimeFormat($input)
    {
        $input = !is_numeric($input) || $input <= 0 ? 0 : $input;

        if ($input > 3600 * 24) {
            $day = intval($input / (3600 * 24));
            $hour = ($input - $day * 3600 * 24) / 3600;
            return $day . '天' . intval($hour) . '小时';
        }

        if ($input < 3600 * 24 && $input > 3600) {
            $hour = intval($input / 3600);
            $mim = ($input - $hour * 3600) / 60;
            return $hour . '小时' . intval($mim) . '分';
        }

        if ($input < 3600 && $input > 60) {
            $min = intval($input / 60);
            $s = $input - $min * 60;
            return $min . ' 分' . intval($s) . '秒';
        }

        return $input . '秒';

    }

    //判断用户终端类型
    public static function getType($userAgent)
    {
        if (strpos($userAgent, "micromessenger") && (strpos($userAgent, "iphone") || strpos($userAgent, "ipod")) && !strpos($userAgent, "windows phone")) {
            //微信 iphone
            return "micromessenger_ipone";
        } elseif (strpos($userAgent, "micromessenger") && strpos($userAgent, "ipad")) {
            //微信 ipad
            return "micromessenger_ipad";
        } elseif (strpos($userAgent, "micromessenger") && strpos($userAgent, "android") && !strpos($userAgent, "windows phone")) {
            //微信 android
            return "micromessenger_android";
        } elseif (strpos($userAgent, "windows phone")) {
            return "windows phone";
        } elseif (strpos($userAgent, "iphone") || strpos($userAgent, "ipod")) {
            return "iphone";
        } elseif (strpos($userAgent, "ipad")) {
            return "ipad";
        } elseif (strpos($userAgent, "android")) {
            return "android";
        } else {
            return "unknown";
        }
    }

    //判断字符串是否完整
    static function getcode($str)
    {
        try {
            $s1 = iconv('UTF-8', 'GBK//IGNORE', $str);
            //dd($s1);
            $s0 = iconv('GBK', 'UTF-8//IGNORE', $s1);
            if ($s0 == $str) {
                return 'utf-8';
            } else {
                return 'gbk';
            }
        } catch (\Exception $e) {
            return '';
        }
    }

    /**
     * 时间戳时间格式化
     * @param $time
     * @return string
     *
     */
    static function formatTime($time)
    {
        $diff = $_SERVER['REQUEST_TIME'] - $time;
        $now_time = time();
        $now_y = date('Y', $now_time);
        $time_y = date('Y', $time);
        $time = $time === NULL || $time > $now_time ? $now_time : intval($time);
        $t = $now_time - $time; //时间差 （秒）
        if ($t == 0)
            $text = '刚刚';
        elseif ($t < 60)
            $text = $t . '秒前'; // 一分钟内
        else if ($t < 60 * 60)
            $text = ceil($t / 60) . '分钟前'; //一小时内
        elseif ($t < 60 * 60 * 24)
            $text = ceil($t / (60 * 60)) . '小时前'; // 一天内
        elseif ($now_y != $time_y)
            $text = date('Y-m-d', $time);
        elseif ($t < 60 * 60 * 24 * 365)
            $text = date('m-d', $time);
        else
            $text = date('Y-m-d', $time);
        return $text;
    }

    /**
     * 去Emoji表情
     * @param $text
     * @return mixed|string
     */
    public static function removeEmoji($text)
    {
        $clean_text = "";
        // Match Emoticons
        $regexEmoticons = '/[\x{1F600}-\x{1F64F}]/u';
        $clean_text = preg_replace($regexEmoticons, '', $text);
        // Match Miscellaneous Symbols and Pictographs
        $regexSymbols = '/[\x{1F300}-\x{1F5FF}]/u';
        $clean_text = preg_replace($regexSymbols, '', $clean_text);
        // Match Transport And Map Symbols
        $regexTransport = '/[\x{1F680}-\x{1F6FF}]/u';
        $clean_text = preg_replace($regexTransport, '', $clean_text);
        // Match Miscellaneous Symbols
        $regexMisc = '/[\x{2600}-\x{26FF}]/u';
        $clean_text = preg_replace($regexMisc, '', $clean_text);
        // Match Dingbats
        $regexDingbats = '/[\x{2700}-\x{27BF}]/u';
        $clean_text = preg_replace($regexDingbats, '', $clean_text);
        return $clean_text;
    }

    /**
     * 数字格式转换
     */
    static function priceFormat($input)
    {

        if (!isset($input)) return '';
        if (!is_numeric($input)) return $input;
        if ($input == intval($input)) return intval($input) . '';
        return ((sprintf("%1\$.2f", $input) * 100) / 100) . '';
    }

    //Luhn
    static function Luhn($no)
    {
        $arr_no = str_split($no);
        $last_n = $arr_no[count($arr_no) - 1];
        krsort($arr_no);
        $i = 1;
        $total = 0;
        foreach ($arr_no as $n) {
            if ($i % 2 == 0) {
                $ix = $n * 2;
                if ($ix >= 10) {
                    $nx = 1 + ($ix % 10);
                    $total += $nx;
                } else {
                    $total += $ix;
                }
            } else {
                $total += $n;
            }
            $i++;
        }
        $total -= $last_n;
        $total *= 9;
        return $last_n == ($total % 10);
    }

    //curl
    static function http_curl($url, $data = '', $is_post = 1)
    {
        $header[] = "Content-type: application/json";//定义content-type
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url . '?' . $data);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        curl_setopt($curl, CURLOPT_POST, $is_post);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        $result = json_decode($output,true);
        //dd($result);
        return $result;
    }

    static function createLinkstring($para)
    {
        $arg = "";
        while (list ($key, $val) = each($para)) {
            if (is_array($val) || is_object($val)) {
                $val = json_encode($val);
            }
            $arg .= $key . "=" . $val . "&";
        }
        //去掉最后一个&字符
        $arg = substr($arg, 0, count($arg) - 2);

        //如果存在转义字符，那么去掉转义
        if (get_magic_quotes_gpc()) {
            $arg = stripslashes($arg);
        }

        return $arg;
    }

    static function clearn_product_image_url($str)
    {
        $str = str_replace(env('IMG_PRODUCT_BEGIN_URL'), '', $str);
        $str = str_replace(env('IMG_PRODUCT_BEGIN_URL_2'), '', $str);
        $str = str_replace(env('IMG_PRODUCT_BEGIN_URL_2S'), '', $str);
        $str = str_replace(env('IMG_PRODUCT_END_URL'), '', $str);
        return $str;
    }

    /**
     * 处理版本号
     * @param $new_version_code
     * @param $platform
     * @return array|int
     */
    static function compare_versions($new_version_code)
    {
        $new_version_code = explode('.', $new_version_code);
        if (count($new_version_code) != 3) {
            return 0;
        }
        $new_version_code = intval($new_version_code[0] . $new_version_code[1] . $new_version_code[2]);
        return $new_version_code;
    }

    /***
     * 定时修改日志权限
     * @return bool
     */
    public static function generateLog()
    {
        try {
            Log::info('凌晨生成日志');
            $log_name = 'laravel-' . date('Y-m-d', time()) . '.log';
            $log_folder_name = storage_path('logs');
            $log_absolute_path = $log_folder_name . DIRECTORY_SEPARATOR . $log_name;
            chmod($log_absolute_path, 0766);
            return true;
        } catch (\Exception $e) {
            Log::info($e);
            return false;
        }
    }

    /***
     * 判断字符串中有没有特殊字符
     * @param $str
     * @return bool|int
     */
    static function hasSpecialChar($str)
    {
        $str = trim($str);
        if (empty($str)) {
            return false;
        }
        return preg_match("/[\'.,:;*?~`!@#$%^&+=)(<>{}]|\]|\[|\/|\\\|\"|\|/", $str);
    }

    /**
     * 统计时间转换
     * 参数：
     *     type         1年2月3日4时5分
     * @return [type]         [
     *         'between' => ['start','end']
     *         'under'   => '1'
     * ]
     */
    static function time_format($begin, $end, $type = 1){
        $arr = [];
        switch($type){
            case 1:
                $year = date('Y',$end) - date('Y',$begin);
                for($a = 0; $a < ($year + 1); $a++){
                    $now = date('Y', $begin);

                    $ar['between'] = [$now . '-1-1', $now . '-12-31'];
                    $ar['under']   = $now . '';
                    $arr[]         = $ar;
                }
                break;
            case 2:
                $begin_year = date('Y', $begin);
                $begin_month = date('Y', $begin);
                $end_month = date('Y', $end);
                $end_month = date('Y', $end);
                for($begin_year; $begin_year < $end_year + 1; $begin_year++){

                }
        }
        return $arr;
    }
}
